package com.jointask;

import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.stream.LongStream;

/**
 * @ClassName: ExecutorServiceCalculator
 * @Author: ZhangYue26
 * @Description: 使用ExecutorService线程池实现计算任务
 * @Date: 2021-04-19
 */
public class ExecutorServiceCalculator implements Callable<Long> {
    private long[] numbers;
    private int from;
    private int to;

    public ExecutorServiceCalculator(long[] numbers, int from, int to) {
        this.numbers = numbers;
        this.from = from;
        this.to = to;
    }

    @Override
    public Long call() throws Exception {
        long total = 0;
        for (int i = from; i <= to; i++) {
            total += numbers[i];
        }
        return total;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        int size = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        java.util.List<Future<Long>> results = new ArrayList<>();
        long[] longs = LongStream.range(1, 9999999).toArray();
        int part = longs.length / size;
        for (int i = 0; i < size; i++) {
            int start = i * part;
            int end = (i == size - 1) ? longs.length - 1 : (i + 1) * part - 1;
            results.add(executorService.submit(new ExecutorServiceCalculator(longs, start, end)));
        }
        long sum = 0;
        for (Future<Long> result : results) {
            sum += result.get();
        }
        System.out.println(sum);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
        executorService.shutdown();
    }
}
